package com.ebupt.migu.music.broadExt.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ebupt.migu.music.broadExt.entity.broadExt.ActListVo;
import com.ebupt.migu.music.broadExt.entity.broadExt.ActivityInfo;
import com.ebupt.migu.music.broadExt.service.BroadExtService;
import com.ebupt.migu.music.schedule.entity.pubBroadcastingActTask.BroadcastActivityInfoVo;
import com.ebupt.migu.music.util.constant.CommonConstant;
import com.ebupt.migu.music.util.enumeration.BroadcastCustomerTagEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@Slf4j
public class BroadExtServiceImpl implements BroadExtService {
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 获取活动列表
     * 
     * @param actListVo
     * @return
     */
    @Override
    public JSONObject actList(ActListVo actListVo) {
        JSONObject object = new JSONObject();
        try {
            log.info("开始筛选活动!===" + actListVo.toString());
            // 活动的基本信息
            List<BroadcastActivityInfoVo> allActList = new ArrayList<>();
            // 获取开始的活动的ID
            Set allActRedis = redisTemplate.opsForSet().members(CommonConstant.startActRedis);
            if (allActList.isEmpty()) {
                object.put("code", "1001");
                object.put("message", "没有进行中的活动");
                object.put("data", null);
                return object;
            }
            Iterator iterator = allActRedis.iterator();
            if (iterator.hasNext()) {
                String next = String.valueOf(iterator.next());
                Object o = redisTemplate.opsForValue().get(next + "_" + CommonConstant.actBaseInfo);
                BroadcastActivityInfoVo infoVo =
                    JSONObject.parseObject(JSON.toJSONString(o), BroadcastActivityInfoVo.class);
                allActList.add(infoVo);
            }
            Map<String, List<BroadcastActivityInfoVo>> collect = null;
            log.info("已开始的活动个数", allActList.size());
            if (allActList.size() > 0) {
                collect = allActList.stream().collect(Collectors.groupingBy(BroadcastActivityInfoVo::getActivityId));
                log.info("第一次筛选");
                // 第一次筛选
                // 判断哪些活动选了店铺或者套餐标签，匹配不到storeId
                String storeId = actListVo.getStoreId();
                if (!StringUtils.isBlank(storeId)) {
                    Iterator<Map.Entry<String, List<BroadcastActivityInfoVo>>> it = collect.entrySet().iterator();
                    while (it.hasNext()) {
                        Map.Entry<String, List<BroadcastActivityInfoVo>> next = it.next();
                        String activityId = next.getKey();
                        BroadcastActivityInfoVo value = next.getValue().get(0);
                        // 客群类型：1-标签客群；2-文件上传【商户ID】；3-手工录入【商户ID】4-全量标签
                        String customerType = value.getCustomerType();
                        if ("1".equals(customerType)) {
                            List<String> tagModuleList = value.getTagModuleList();
                            if (tagModuleList != null && tagModuleList.size() > 0) {
                                if (tagModuleList.contains("1") || tagModuleList.contains("4")) {
                                    Boolean member = redisTemplate.opsForSet()
                                        .isMember(activityId + "_" + CommonConstant.storeIdRedis, storeId);
                                    if (!member) {
                                        collect.remove(activityId);
                                    }
                                }
                            }
                        } else if ("2".equals(customerType)) {
                            Boolean member = redisTemplate.opsForSet()
                                .isMember(activityId + "_" + CommonConstant.customerFileRedis, storeId);
                            if (!member) {
                                collect.remove(activityId);
                            }
                        } else if ("3".equals(customerType)) {
                            Boolean member = redisTemplate.opsForSet()
                                .isMember(activityId + "_" + CommonConstant.customerInputRedis, storeId);
                            if (!member) {
                                collect.remove(activityId);
                            }
                        }

                    }
                }
                // 第二次筛选
                // 判断板块ID 是否符合条件
                log.info("第二次筛选");
                String tagId = actListVo.getTagId();
                if (!StringUtils.isBlank(tagId)) {
                    Iterator<Map.Entry<String, List<BroadcastActivityInfoVo>>> it = collect.entrySet().iterator();
                    while (it.hasNext()) {
                        Map.Entry<String, List<BroadcastActivityInfoVo>> next = it.next();
                        String activityId = next.getKey();
                        BroadcastActivityInfoVo value = next.getValue().get(0);
                        // 运营触点：1-Banner；2-歌单广场；3-语音播报
                        String activityType = value.getActivityType();
                        if (tagId.equals(activityType)) {
                            String sectionId = actListVo.getSectionId();
                            if (!StringUtils.isBlank(sectionId)) {
                                if ("2".equals(tagId) && "2".equals(activityType)) {
                                    String section = value.getSection();
                                    if (section != null && !sectionId.equals(section)) {
                                        collect.remove(activityId);
                                    }
                                }
                                if ("3".equals(tagId) && "3".equals(activityType)) {
                                    String section = value.getRadioSection();
                                    if (section != null && !sectionId.equals(section)) {
                                        collect.remove(activityId);
                                    }
                                }
                            }

                        } else {
                            collect.remove(activityId);
                        }

                    }
                }
                // 第三次筛选
                log.info("第三次筛选");
                // 判断商户所属音乐馆标签
                String playlistTags = actListVo.getPlaylistTags();
                if (!StringUtils.isBlank(playlistTags)) {
                    List<String> playlist = Arrays.asList(playlistTags.split(","));
                    Iterator<Map.Entry<String, List<BroadcastActivityInfoVo>>> it = collect.entrySet().iterator();
                    while (it.hasNext()) {
                        Map.Entry<String, List<BroadcastActivityInfoVo>> next = it.next();
                        String activityId = next.getKey();
                        BroadcastActivityInfoVo value = next.getValue().get(0);
                        // 客群类型：1-标签客群；2-文件上传【商户ID】；3-手工录入【商户ID】4-全量标签
                        String customerType = value.getCustomerType();
                        if ("1".equals(customerType)) {
                            log.info("判断音乐馆标签===:" + activityId);
                            List<String> tagModuleList = value.getTagModuleList();
                            // 判断活动有没有音乐馆标签，如果有，就要判断此活动的标签是否在用户属性中
                            if (tagModuleList != null && tagModuleList.size() > 0 && tagModuleList.contains("2")) {
                                // 获取音乐馆标签
                                String redisStr = BroadcastCustomerTagEnum.playList.getRedisStr();
                                Set members = redisTemplate.opsForSet().members(activityId + "_" + redisStr);
                                if (members != null && members.size() > 0) {
                                    String[] objects = (String[])members.toArray();
                                    for (String str : objects) {
                                        if (!playlist.contains(str)) {
                                            collect.remove(activityId);
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                // 第四次筛选
                log.info("第四次筛选");
                // 判断语音播报标签
                String radioTags = actListVo.getRadioTags();
                if (!StringUtils.isBlank(radioTags)) {
                    List<String> radioList = Arrays.asList(radioTags.split(","));
                    Iterator<Map.Entry<String, List<BroadcastActivityInfoVo>>> it = collect.entrySet().iterator();
                    while (it.hasNext()) {
                        Map.Entry<String, List<BroadcastActivityInfoVo>> next = it.next();
                        String activityId = next.getKey();
                        BroadcastActivityInfoVo value = next.getValue().get(0);
                        // 客群类型：1-标签客群；2-文件上传【商户ID】；3-手工录入【商户ID】4-全量标签
                        String customerType = value.getCustomerType();
                        if ("1".equals(customerType)) {
                            log.info("判断语音播报标签===:" + activityId);
                            // 判断活动有没有语音播报标签，如果有，就要判断此活动的标签是否在用户属性中
                            List<String> tagModuleList = value.getTagModuleList();
                            if (tagModuleList != null && tagModuleList.size() > 0 && tagModuleList.contains("3")) {
                                // 获取语音播报标签
                                String redisStr = BroadcastCustomerTagEnum.broadcastTab.getRedisStr();
                                Set members = redisTemplate.opsForSet().members(activityId + "_" + redisStr);
                                if (members != null && members.size() > 0) {
                                    String[] objects = (String[])members.toArray();
                                    for (String str : objects) {
                                        if (!radioList.contains(str)) {
                                            collect.remove(activityId);
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            log.info("普通标签筛选结束");
            log.info("全量标签筛选开始");
            // 查询全量标签
            List<BroadcastActivityInfoVo> allTagList = new ArrayList<>();
            Set allAct = redisTemplate.opsForSet().members(CommonConstant.allActRedis);
            Iterator allActIterator = allAct.iterator();
            if (allActIterator.hasNext()) {
                String next = String.valueOf(iterator.next());
                Object o = redisTemplate.opsForValue().get(next + "_" + CommonConstant.actBaseInfo);
                BroadcastActivityInfoVo infoVo =
                    JSONObject.parseObject(JSON.toJSONString(o), BroadcastActivityInfoVo.class);
                allTagList.add(infoVo);
            }
            log.info("全量标签的个数:" + allTagList.size());
            Map<String, List<BroadcastActivityInfoVo>> allTagCollect = null;
            if (allTagList.size() > 0) {
                allTagCollect =
                    allTagList.stream().collect(Collectors.groupingBy(BroadcastActivityInfoVo::getActivityId));
                // 筛选全量标签
                log.info("筛选全量标签");
                // 因为是全量标签，所以只用判断板块ID 是否符合条件
                String tagId = actListVo.getTagId();
                if (!StringUtils.isBlank(tagId)) {
                    Iterator<Map.Entry<String, List<BroadcastActivityInfoVo>>> it = allTagCollect.entrySet().iterator();
                    while (it.hasNext()) {
                        Map.Entry<String, List<BroadcastActivityInfoVo>> next = it.next();
                        String activityId = next.getKey();
                        BroadcastActivityInfoVo value = next.getValue().get(0);
                        // 运营触点：1-Banner；2-歌单广场；3-语音播报
                        String activityType = value.getActivityType();
                        if (tagId.equals(activityType)) {
                            String sectionId = actListVo.getSectionId();
                            if (!StringUtils.isBlank(sectionId)) {
                                if ("2".equals(tagId) && "2".equals(activityType)) {
                                    String section = value.getSection();
                                    if (section != null && !sectionId.equals(section)) {
                                        allTagCollect.remove(activityId);
                                    }
                                }
                                if ("3".equals(tagId) && "3".equals(activityType)) {
                                    String section = value.getRadioSection();
                                    if (section != null && !sectionId.equals(section)) {
                                        allTagCollect.remove(activityId);
                                    }
                                }
                            }

                        } else {
                            allTagCollect.remove(activityId);
                        }

                    }
                }
            }
            log.info("全量标签筛选结束");
            List<ActivityInfo> activityInfos = new ArrayList<>();
            // 组装返回数据
            log.info("组装普通标签数据");
            Iterator<Map.Entry<String, List<BroadcastActivityInfoVo>>> it = collect.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<String, List<BroadcastActivityInfoVo>> next = it.next();
                BroadcastActivityInfoVo value = next.getValue().get(0);
                ActivityInfo activityInfo = new ActivityInfo();
                BeanUtils.copyProperties(value, activityInfo);
                activityInfo.setActivityId(value.getCmsActivityId());
                activityInfos.add(activityInfo);
            }
            // 组装返回数据
            log.info("组装全量标签数据");
            Iterator<Map.Entry<String, List<BroadcastActivityInfoVo>>> allTagit = allTagCollect.entrySet().iterator();
            while (allTagit.hasNext()) {
                Map.Entry<String, List<BroadcastActivityInfoVo>> next = allTagit.next();
                BroadcastActivityInfoVo value = next.getValue().get(0);
                ActivityInfo activityInfo = new ActivityInfo();
                BeanUtils.copyProperties(value, activityInfo);
                activityInfo.setActivityId(value.getCmsActivityId());
                activityInfos.add(activityInfo);
            }
            object.put("code", "0000");
            object.put("message", "SUCCESS");
            object.put("data", activityInfos);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("获取活动列表错误:" + e.getMessage());
            object.put("code", "9999");
            object.put("message", "SYSTEM ERROR");
            object.put("data", null);
        }
        return object;
    }
}
